﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Intel_Client_GUI
{
	/// <summary>
	/// VirutalKeyboard.xaml 的交互逻辑
	/// </summary>
	public partial class VirtualKeyboard : UserControl
	{
	
		public VirtualKeyboard()
		{
			this.InitializeComponent();
			this.AddHandler(Key.VkPressedEvent,new RoutedEventHandler(EventHandler),true);
		   			
		}
		public static DependencyProperty KeyPressedProperty = DependencyProperty.Register(
			"KeyCode",typeof(int),typeof(VirtualKeyboard));
		
		public delegate void OnResetColor(); 
			
		public static readonly OnResetColor ResetColorEvent;
		
		public int KeyCode
		{
			get{return (int)(this.GetValue(VirtualKeyboard.KeyPressedProperty));}
			set{this.SetValue(VirtualKeyboard.KeyPressedProperty,value);}
		}
		
		public static DependencyProperty KeyColorsProperty = DependencyProperty.Register(
			"KeyColors",typeof(Dictionary<string,int>),typeof(VirtualKeyboard));
		
		protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
		{
			if(e.Property == VirtualKeyboard.KeyColorsProperty)
			{
				SetOp(this.FirstRow);
				SetOp(this.SecondRow);
				SetOp(this.ThirdRow);
				SetOp(this.ForthRow);
				SetOp(this.FifthRow);
				var dic = e.NewValue  as Dictionary<string,int>;
				if(dic ==null)
					return;
				foreach(KeyValuePair<string,int> pair in dic)
				{
					Key VKey = this.FindName(pair.Key) as Key;
					if(VKey ==null)
					{
						continue;
					}
					VKey.Masker.Opacity =(double) pair.Value/100;
				}
			}
			else
				base.OnPropertyChanged(e);
		}
			
		public Dictionary<string,int> KeyColors
		{
			get
			{
				return (Dictionary<string,int>)(this.GetValue(VirtualKeyboard.KeyColorsProperty));
			}
			set{System.Windows.MessageBox.Show("2");this.SetValue(VirtualKeyboard.KeyColorsProperty,value);}
		}
	
		public void EventHandler(object sender,RoutedEventArgs e)
		{
			var Vk = e.OriginalSource as Key;
			if(Vk!=null)
			{
				this.KeyCode =(int) Vk.KeyValue;
			}
			e.Handled=true;
			RoutedEventArgs newEventArgs = new RoutedEventArgs(VirtualKeyboard.VKPressedEvent,this);
            RaiseEvent(newEventArgs);
		}
		
		public static readonly RoutedEvent VKPressedEvent = EventManager.RegisterRoutedEvent("VKPressedPressed",RoutingStrategy.Bubble,typeof(RoutedEventHandler), typeof(VirtualKeyboard));
		
		private void SetOp(Grid g)
		{
			for(int i=0;i<VisualTreeHelper.GetChildrenCount(g);i++)
			{
				var k = VisualTreeHelper.GetChild(g,i) as Key;
				if(k==null)
					continue;
				k.KeyOp=0;
			}
		}
	}
}